#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <memory>
#include <cstring>
#include <cerrno>

struct FileContent {
    int32_t size;
    char data[0];
};

void Read()
{
    std::ifstream ifs("file.bin", std::ifstream::in | std::ifstream::binary);
    ifs.seekg(0, ifs.end);
    int32_t length = ifs.tellg();
    ifs.seekg (0, ifs.beg);

    auto buffer = std::make_unique<uint8_t[]>(length);
    ifs.read(reinterpret_cast<char *>(buffer.get()), length);

    std::vector<std::string> strs;
    struct FileContent *pFc = reinterpret_cast<struct FileContent *>(buffer.get());

    for (int32_t offset = 0, i = 0; offset < pFc->size; i++) {
        strs.emplace_back(pFc->data + offset);
        offset += strs[i].length() + 1;
    }

    for (const auto &str : strs) {
        std::cout << str << std::endl;
    }
}

void Write(int argc, const char **argv)
{
    int32_t strSize = 0;
    std::vector<std::string> strs;
    for (int32_t i = 0; i < argc; i++) {
        strs.push_back(argv[i]);
        strSize += strs[i].length() + 1;
    }

    int32_t contentSize = strSize + sizeof(FileContent);
    auto buffer = std::make_unique<uint8_t[]>(contentSize);
    auto pFc = reinterpret_cast<struct FileContent *>(buffer.get());
    pFc->size = strSize;

    int32_t offset = 0;
    for (const auto &str : strs) {
        memcpy(pFc->data + offset, str.c_str(), str.length() + 1);
        offset += str.length() + 1;
    }

    std::ofstream ofs("file.bin", std::ofstream::out | std::ofstream::binary);
    ofs.write(reinterpret_cast<const char *>(buffer.get()), contentSize);
    ofs.close();
}

int main(int argc, const char **argv)
{
    std::ofstream ofs("/1");
    std::cout << ofs.is_open() << std::endl;
    std::cout << errno << std::endl;

    ofs << 1;
    if (argc == 1) {
        Read();
    } else {
        Write(argc, argv);
    }
}
